﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CloudShot.Utils.Encoding;
using ImageProcessor.Imaging.Formats;

namespace GifPreformanceTest
{
  class Program
  {
    static void Main(string[] args)
    {
      List<Bitmap> bitmaps = Directory.EnumerateFiles(@"C:\Work\cloudshot\Experimental\GifPreformanceTest\Frames", "*.bmp", SearchOption.AllDirectories).Select(x => Image.FromFile(x) as Bitmap).ToList();

      int width = bitmaps[0].Width;
      int height = bitmaps[0].Height; 
      var encoder = new AnimatedGifEncoder(width, height, 15);
      encoder.SetRepeat(0); //if checked, 0 else -1

      encoder.Start();

        Stopwatch stopWatch = new Stopwatch();

        stopWatch.Start();
      foreach (var bitmap in bitmaps)
      {
        encoder.AddFrame(bitmap);
      }

      Image result = encoder.Finish();

      Console.WriteLine(string.Format("Old encoder time {0}", stopWatch.ElapsedMilliseconds));

      result.Save(@"C:\Work\res.gif");

        

      var stream = new MemoryStream();
      stopWatch.Restart();
        EncodeNew(stream, bitmaps, width, height);
        Console.WriteLine(string.Format("new encoder time {0}", stopWatch.ElapsedMilliseconds));

        File.WriteAllBytes(@"C:\Work\newres.gif", stream.GetBuffer());

        Console.ReadKey();
    }

    private static void EncodeNew(MemoryStream stream,IEnumerable<Bitmap> bitmaps, int width, int height)
      {
          
          GifEncoder encoder = new GifEncoder(stream, width, height);

          foreach (var bitmap in bitmaps)
          {

              var frame = new GifFrame();
              frame.Image = bitmap;
              frame.Delay = 1000/12; //12 frames per second
              encoder.AddFrame(frame);
          }

      
          
      }
  }
}
